package com.wildworld.coreimpl;

import com.wildworld.core.IMap;
import com.wildworld.core.IWorld;
import com.wildworld.core.worldobjects.WorldObject;
import org.apache.commons.collections.Closure;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * @author gzhebrakov
 *         Date: 20.07.12
 *         Time: 21:06
 */

public class WildWorldImpl implements IWorld {

    private boolean live = true;
    private IMap map;
    private List<WorldObject> objects = new LinkedList<WorldObject>();

    @Override
    public void setWorldMap(IMap map) {
        this.map = map;
    }

    @Override
    public IMap getWorldMap() {
        return map;
    }

    @Override
    public Iterator<WorldObject> getWorldObjects() {
        return objects.iterator();
    }

    @Override
    public void addWorldObject(WorldObject obj) {
        objects.add(obj);
    }

    @Override
    public WorldObject findObjectById(final String id) {
        return (WorldObject) CollectionUtils.find(objects, new Predicate() {
            @Override
            public boolean evaluate(Object o) {
                return !id.isEmpty() && id.equals(((WorldObject) o).getUuid());
            }
        });
    }

    @Override
    public void stop() {
        live = false;
    }

    @Override
    public void run() {
        while (live){
            try {
                map.setWorldObjects(objects);
                Thread.currentThread().sleep(250);
                CollectionUtils.forAllDo(objects, new Closure() {
                    @Override
                    public void execute(Object o) {
                        ((WorldObject)o).doAction(map, WildWorldImpl.this);
                    }
                });
                map.reDraw(objects);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

}